﻿using CloOpenSDK;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.Configuration;
using Sino.CapacityCloud.Services.Models;
using Sino.Common.Utilities;
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Sino.CapacityCloud.Services
{

    public class FakeSmsSender
        : ISmsSender
    {

        private readonly IHttpContextAccessor _httpContextAccessor;

        public IConfigurationSection Configuration { get; private set; }

        public FakeSmsSender(IHttpContextAccessor httpContextAccessor)
        {
            this._httpContextAccessor = httpContextAccessor;
        }

        public bool ValidatePhoneFormat(string phoneNumber)
        {
            //return StringValidationUtility.IsChineseMobilePhoneNumber(phoneNumber);
            return phoneNumber.IsPhoneNumber();
        }

        protected async Task<SMSResult> SendSms(SmsDom csd)
        {
            return await Task.FromResult(new SMSResult() { statusCode = "000000" });
        }

        public void SendSms(string phonNumber, string code)
        {
            this.SendSmsAsync(phonNumber, code).GetAwaiter().GetResult();
        }

        public async Task<SmsRequestResult> SendSmsAsync(string phonNumber, string code)
        {
            if (!this.ValidatePhoneFormat(phonNumber))
            {
                throw new ArgumentOutOfRangeException("phonNumber");
            }
            SmsDom dom = new SmsDom();
            dom.PhoneLists.Add(phonNumber);
            dom.TemplateID = "27026";
            dom.TemplateData.Add(code);
            dom.TemplateData.Add("2");
            var r = await SendSms(dom);

            // Embed the code to the response stream.
            this._httpContextAccessor.HttpContext.Response.Headers.Add("Code", code);

            switch (r.statusCode)
            {
                case "000000":
                    return SmsRequestResult.Success;

                case "172002":
                    return SmsRequestResult.WrongPhoneNumber;

                case "172003":
                    return SmsRequestResult.ServerError;

                default:
                    return SmsRequestResult.ServerError;
            }
        }

    }

}